package eai.tp2.camerasupplier;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

@WebService(targetNamespace = "http://eai/tp2/supplier", serviceName = "CameraSupplierService")
@SOAPBinding(style = SOAPBinding.Style.RPC)
public class CameraSupplier {

	List<Element> database = null;

	private void createDatabaseInMemory() {
		if (database == null) {
			try {
				loadDatabase(setupXMLDatabase());
			} catch (JDOMException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private void loadDatabase(List<String> XMLDatabase) throws JDOMException,
			IOException {
		database = new ArrayList<Element>();
		SAXBuilder builder = null;
		for (String filename : XMLDatabase) {
			builder = new SAXBuilder(true);
			builder.setFeature(
					"http://apache.org/xml/features/validation/schema", true);		
			File dir = new File(System.getProperty("user.dir"));
			Document doc = builder.build(dir.getParent() + File.separatorChar +"server"+ File.separatorChar +"default"+ File.separatorChar +"deploy"+ File.separatorChar + "data"+ File.separatorChar + filename);
			Element root = doc.getRootElement();
			List<Element> cameras = (List<Element>) root.getChildren();
			database.addAll(cameras);

		}
	}

	private List<String> setupXMLDatabase() {
		List<String> filenames = new ArrayList<String>();
		File dir = new File(System.getProperty("user.dir"));
		File folder = new File(dir.getParent() + File.separatorChar +"server"+ File.separatorChar +"default"+ File.separatorChar +"deploy"+ File.separatorChar + "data"+ File.separatorChar);
		if (folder != null) {
			File[] list = folder.listFiles();
			if (list != null) {
				for (int i = 0; i < list.length; i++) {
					if (list[i].isFile())
						if (list[i].getName().toLowerCase().endsWith(".xml"))
							filenames.add(list[i].getName());
				}
			}
		}
		return filenames;
	}

	private List<Element> getResults(String query) {
		List<Element> results = new ArrayList<Element>();
		for (Element camera : database) {
			if (camera.getChild("name").getValue().toLowerCase().contains(
					query.toLowerCase())) {				
				Element temp = (Element) camera.clone();
				Element el = new Element("brand");
				el.addContent(((Element) camera.getParent())
						.getAttributeValue("brand"));
				Element el1 = new Element("price");
				el1.addContent(getPrice());
				temp.addContent(el);
				temp.addContent(el1);
				results.add(temp);
			}
		}
		return results;
	}

	private String getPrice() {
		Random r = new Random();
		// from 100 to 1000
		return String.valueOf(100 + r.nextInt(901));
	}

	private String getXMLResult(List<Element> results) {
		Element root = new Element("Results");
		Namespace xsi = Namespace.getNamespace("xsi",
				"http://www.w3.org/2001/XMLSchema-instance");
		root.setAttribute("noNamespaceSchemaLocation", "Results.xsd", xsi);
		Document doc = new Document();
		root.addContent(results);
		doc.setRootElement(root);
		XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
		return outputter.outputString(doc);
	}

	private void addAtribute(Element el, String attribute, String tag) {

		Element temp = new Element(tag);
		temp.addContent(attribute);
		el.addContent(temp);
	}

	@WebMethod
	public String search(String query) {
		createDatabaseInMemory();
		String xmlResult = getXMLResult(getResults(query.trim()));
		System.out.println(xmlResult);
		try {
			return new String(xmlResult.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			System.out.println("[Error] Error enconding to UTF-8");
			return "";
		}
	}

	public static void main(String args[]) {
		System.out.println("Result::\n"
				+ new CameraSupplier().search(" panasonic "));
	}
}
